import React from 'react';
import {
  Box,
  Paper,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  Tooltip,
  Alert,
} from '@mui/material';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import TrendingDownIcon from '@mui/icons-material/TrendingDown';
import { ReverseCalculation } from '../../services/storage';
import { CalculationResult } from '../../types/calculation';

interface PerformanceAnalysisProps {
  calculations: CalculationResult[];
  reverseCalculations: ReverseCalculation[];
}

interface PerformanceData {
  productId: string;
  productName: string;
  bankName: string;
  expectedRates: {
    timeLabel: string;
    rate: number;
    expectedInterest: number;
  }[];
  actualRate: number;
  expectedInterest: number;
  actualInterest: number;
  principal: number;
  periodDays: number;
  performance: {
    rateDeviation: number;  // 实际年化与预期年化的偏差百分比
    interestDeviation: number;  // 实际收益与预期收益的偏差百分比
    status: 'above' | 'below' | 'equal';  // 表现状态
  };
}

const PerformanceAnalysis: React.FC<PerformanceAnalysisProps> = ({
  calculations,
  reverseCalculations,
}) => {
  // 分析产品表现
  const analyzePerformance = (): PerformanceData[] => {
    const performanceData: PerformanceData[] = [];
    
    // 遍历所有实际收益数据
    reverseCalculations.forEach(actual => {
      // 计算投资天数（如果没有提供）
      const periodDays = actual.periodDays || Math.floor(
        (new Date(actual.endDate).getTime() - new Date(actual.startDate).getTime()) / 
        (1000 * 60 * 60 * 24)
      );

      // 查找对应的预期收益数据
      const expected = calculations.find(calc => 
        calc.productId === actual.productId
      );
      
      if (expected) {
        // 获取并计算每个时间标签对应的预期收益率和预期收益
        const expectedRates = expected.rates.map(rate => {
          // 计算该利率下的预期收益
          const expectedInterest = actual.principal * rate.rate / 100 * periodDays / 365;
          return {
            timeLabel: rate.timeLabel,
            rate: rate.rate,
            expectedInterest: expectedInterest,
          };
        });
        
        // 计算平均预期年化收益率
        const avgExpectedRate = expectedRates.reduce((sum, rate) => sum + rate.rate, 0) / expectedRates.length;
        
        // 计算平均预期收益
        const avgExpectedInterest = expectedRates.reduce((sum, rate) => sum + rate.expectedInterest, 0) / expectedRates.length;
        
        // 计算收益率和收益额的偏差
        const rateDeviation = ((actual.actualRate - avgExpectedRate) / avgExpectedRate) * 100;
        const interestDeviation = ((actual.profit - avgExpectedInterest) / avgExpectedInterest) * 100;
        
        performanceData.push({
          productId: actual.productId,
          productName: actual.productName,
          bankName: actual.bankName,
          expectedRates,
          actualRate: actual.actualRate,
          expectedInterest: avgExpectedInterest,
          actualInterest: actual.profit,
          principal: actual.principal,
          periodDays: periodDays,
          performance: {
            rateDeviation,
            interestDeviation,
            status: rateDeviation > 0 ? 'above' : rateDeviation < 0 ? 'below' : 'equal',
          },
        });
      }
    });
    
    return performanceData;
  };

  const formatMoney = (amount: number): string => {
    return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  };

  const formatRate = (rate: number): string => {
    return `${rate.toFixed(2)}%`;
  };

  const formatDeviation = (deviation: number): string => {
    const sign = deviation > 0 ? '+' : '';
    return `${sign}${deviation.toFixed(2)}%`;
  };

  const getDeviationColor = (deviation: number): string => {
    if (deviation > 0) return 'success.main';
    if (deviation < 0) return 'error.main';
    return 'text.primary';
  };

  const performanceData = analyzePerformance();

  if (performanceData.length === 0) {
    return (
      <Alert severity="info" sx={{ mt: 3 }}>
        需要同时有收益预测和收益反算的数据才能进行对比分析。请先添加相应数据。
      </Alert>
    );
  }

  return (
    <Box sx={{ mt: 3 }}>
      <Typography variant="h6" gutterBottom>
        数据对比分析
      </Typography>
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>产品信息</TableCell>
              <TableCell align="right">投资金额</TableCell>
              <TableCell align="right">投资天数</TableCell>
              <TableCell>预期年化</TableCell>
              <TableCell align="right">预期收益</TableCell>
              <TableCell align="right">实际年化</TableCell>
              <TableCell align="right">实际收益</TableCell>
              <TableCell align="right">表现</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {performanceData.map((data) => (
              <TableRow key={data.productId}>
                <TableCell>
                  <Typography variant="body2" gutterBottom>
                    {data.bankName}
                  </Typography>
                  <Typography variant="body2" color="textSecondary">
                    {data.productName}
                  </Typography>
                </TableCell>
                <TableCell align="right">
                  {formatMoney(data.principal)}
                </TableCell>
                <TableCell align="right">
                  {data.periodDays > 0 ? `${data.periodDays}天` : '-'}
                </TableCell>
                <TableCell>
                  {data.expectedRates.map((rate, index) => (
                    <Typography key={index} variant="body2" gutterBottom>
                      {rate.timeLabel}: {formatRate(rate.rate)}
                      <Typography variant="caption" display="block" color="textSecondary">
                        预期收益: {formatMoney(rate.expectedInterest)}
                      </Typography>
                    </Typography>
                  ))}
                </TableCell>
                <TableCell align="right">
                  {formatMoney(data.expectedInterest)}
                </TableCell>
                <TableCell align="right">
                  <Typography sx={{ color: getDeviationColor(data.performance.rateDeviation) }}>
                    {formatRate(data.actualRate)}
                  </Typography>
                  <Typography variant="caption" sx={{ color: getDeviationColor(data.performance.rateDeviation) }}>
                    ({formatDeviation(data.performance.rateDeviation)})
                  </Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography sx={{ color: getDeviationColor(data.performance.interestDeviation) }}>
                    {formatMoney(data.actualInterest)}
                  </Typography>
                  <Typography variant="caption" sx={{ color: getDeviationColor(data.performance.interestDeviation) }}>
                    ({formatDeviation(data.performance.interestDeviation)})
                  </Typography>
                </TableCell>
                <TableCell align="right">
                  <Tooltip title={
                    `年化收益${Math.abs(data.performance.rateDeviation).toFixed(2)}%${
                      data.performance.status === 'above' ? '高于' : '低于'
                    }预期`
                  }>
                    <Chip
                      icon={data.performance.status === 'above' ? <TrendingUpIcon /> : <TrendingDownIcon />}
                      label={data.performance.status === 'above' ? '优于预期' : '低于预期'}
                      color={data.performance.status === 'above' ? 'success' : 'error'}
                      size="small"
                    />
                  </Tooltip>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </Box>
  );
};

export default PerformanceAnalysis;